import { dbUtils } from '../core'

export interface StoreShopFoodRow {
    id: string
    store_id: string
    name: string
    sub_name: string
    category_id: string
    spec_type: number
    is_enable_grade: number
    is_order_discount: number
    is_group: number
    commission: number
    content: string
    is_weight: number
    stalls: string
    sort: number
    status: number
    is_delete: number
    create_time: number
    is_write_food: number
    is_user: number
}

export const storeShopFoodRepository = {
    upsertBatch(rows: StoreShopFoodRow[]): void {
        if (!rows || rows.length === 0) return
        dbUtils.transaction(() => {
            const sql = `INSERT INTO store_shop_food (
                id, store_id, name, sub_name, category_id, spec_type, is_enable_grade, is_order_discount,
                is_group, commission, content, is_weight, stalls, sort, status, is_delete, create_time,
                is_write_food, is_user
            ) VALUES (
                ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
            )
            ON CONFLICT(id) DO UPDATE SET
                store_id=excluded.store_id,
                name=excluded.name,
                sub_name=excluded.sub_name,
                category_id=excluded.category_id,
                spec_type=excluded.spec_type,
                is_enable_grade=excluded.is_enable_grade,
                is_order_discount=excluded.is_order_discount,
                is_group=excluded.is_group,
                commission=excluded.commission,
                content=excluded.content,
                is_weight=excluded.is_weight,
                stalls=excluded.stalls,
                sort=excluded.sort,
                status=excluded.status,
                is_delete=excluded.is_delete,
                create_time=excluded.create_time,
                is_write_food=excluded.is_write_food,
                is_user=excluded.is_user,
                updated_at=CURRENT_TIMESTAMP
            `
            for (const r of rows) {
                dbUtils.execute(sql, [
                    r.id, r.store_id, r.name, r.sub_name, r.category_id, r.spec_type, r.is_enable_grade, r.is_order_discount,
                    r.is_group, r.commission, r.content, r.is_weight, r.stalls, r.sort, r.status, r.is_delete, r.create_time,
                    r.is_write_food, r.is_user
                ])
            }
        })
    },

    listByStore(store_id: string, category_id?: string) {
        if (category_id) {
            return dbUtils.query(
                `SELECT * FROM store_shop_food WHERE store_id = ? AND category_id = ? AND is_delete = 0 ORDER BY sort ASC, name ASC`,
                [store_id, category_id]
            )
        }
        return dbUtils.query(
            `SELECT * FROM store_shop_food WHERE store_id = ? AND is_delete = 0 ORDER BY sort ASC, name ASC`,
            [store_id]
        )
    }
}

export default storeShopFoodRepository


